<?php
declare(strict_types=1);
/**
 * MineAdmin is committed to providing solutions for quickly building web applications
 * Please view the LICENSE file that was distributed with this source code,
 * For the full copyright and license information.
 * Thank you very much for using MineAdmin.
 *
 * @Author X.Mo<root@imoi.cn>
 * @Link   https://gitee.com/xmo/MineAdmin
 */

namespace App\Box\Mapper;

use App\Box\Model\BoxInfo;
use App\Lib\AdminEnum;
use Hyperf\Coroutine\Exception\ParallelExecutionException;
use Hyperf\Coroutine\Parallel;
use Hyperf\Database\Model\Builder;
use Hyperf\Di\Annotation\Inject;
use Mine\Abstracts\AbstractMapper;
use Whoops\Exception\ErrorException;

/**
 * 盒子列表Mapper类
 */
class BoxInfoMapper extends AbstractMapper
{
    /**
     * @var BoxInfo
     */
    public $model;


    #[Inject]
    protected BoxProductMapper $boxProductMapper;

    public function assignModel()
    {
        $this->model = BoxInfo::class;
    }

    /**
     * 搜索处理器
     * @param Builder $query
     * @param array $params
     * @return Builder
     */
    public function handleSearch(Builder $query, array $params): Builder
    {

        // ID
        if (isset($params['id']) && filled($params['id'])) {
            $query->where('id', '=', $params['id']);
        }

        // 盒子分类id
        if (isset($params['category_id']) && filled($params['category_id'])) {
            $query->where('category_id', '=', $params['category_id']);
        }

        // 盒子名称
        if (isset($params['name']) && filled($params['name'])) {
            $query->where('name', 'like', '%' . $params['name'] . '%');
        }

        // 盒子价格
        if (isset($params['price']) && filled($params['price'])) {
            $query->where('price', '=', $params['price']);
        }

        // 盒子背景图
        if (isset($params['img']) && filled($params['img'])) {
            $query->where('img', 'like', '%' . $params['img'] . '%');
        }

        // 盒子风格id
        if (isset($params['box_style_id']) && filled($params['box_style_id'])) {
            $query->where('box_style_id', '=', $params['box_style_id']);
        }

        // 排序
        if (isset($params['sort']) && filled($params['sort'])) {
            $query->where('sort', '=', $params['sort']);
        }

        // 1:变价模式 2：变物模式 3：活动箱子
        if (isset($params['mode_type']) && filled($params['mode_type'])) {
            $query->where('mode_type', '=', $params['mode_type']);
        }

        // 售价系数
        if (isset($params['price_coefficient']) && filled($params['price_coefficient'])) {
            $query->where('price_coefficient', '=', $params['price_coefficient']);
        }

        // 每日活动开箱次数
        if (isset($params['activity_num']) && filled($params['activity_num'])) {
            $query->where('activity_num', '=', $params['activity_num']);
        }

        // 每日活动充值金额
        if (isset($params['activity_price']) && filled($params['activity_price'])) {
            $query->where('activity_price', '=', $params['activity_price']);
        }

        // 活动开始时间
        if (isset($params['activity_start']) && filled($params['activity_start'])) {
            $query->where('activity_start', '=', $params['activity_start']);
        }

        // 活动结束时间
        if (isset($params['activity_end']) && filled($params['activity_end'])) {
            $query->where('activity_end', '=', $params['activity_end']);
        }

        // 是否展示的箱子(1展示，2:隐藏）
        if (isset($params['status']) && filled($params['status'])) {
            $query->where('status', '=', $params['status']);
        }

        // 创建者
        if (isset($params['created_by']) && filled($params['created_by'])) {
            $query->where('created_by', '=', $params['created_by']);
        }

        // 创建时间
        if (isset($params['create_time']) && filled($params['create_time'])) {
            $query->where('create_time', '=', $params['create_time']);
        }

        // 更新时间
        if (isset($params['update_time']) && filled($params['update_time'])) {
            $query->where('update_time', '=', $params['update_time']);
        }

        // 删除
        if (isset($params['delete_time']) && filled($params['delete_time'])) {
            $query->where('delete_time', '=', $params['delete_time']);
        }

        return $query;
    }

    public function updateBoxMode($params)
    {
        $parallel = new Parallel();
        $sendMesTitle = '';
        switch ($params['type']) {
            case \App\Box\Model\BoxInfo::MODE_TYPE_PRICE : //变价箱子
                $boxIds = $this->model::query()
                    ->where('mode_type', $params['type'])
                    ->where('status', AdminEnum::STATUS_YES)->pluck('id');
                foreach ($boxIds as $boxId) {
                    $parallel->add(function () use ($boxId) {
                        $this->boxProductMapper->changeBoxPriceUpdate($boxId);
                        return [];
                    });
                }
                $sendMesTitle = '【变化箱子】';
                break;
            case \App\Box\Model\BoxInfo::MODE_TYPE_GOODS : //变物箱子
                $boxIds = $this->model::query()
                    ->where('mode_type', $params['type'])
                    ->where('status', AdminEnum::STATUS_YES)->pluck('id');
                foreach ($boxIds as $boxId) {
                    $parallel->add(function () use ($boxId) {
                        $this->boxProductMapper->changeBoxGoodsUpdate($boxId, $this->boxProductMapper::UPDATE_BOX_PRICE_NO);
                        return [];
                    });
                }
                $sendMesTitle = '【变物箱子】';
                break;
            case \App\Box\Model\BoxInfo::MODE_TYPE_ACTIVITY : //活动箱子
                $boxIds = $this->model::query()
                    ->where('mode_type', $params['type'])
                    ->where('status', AdminEnum::STATUS_YES)->pluck('id');
                foreach ($boxIds as $boxId) {
                    $parallel->add(function () use ($boxId) {
                        $this->boxProductMapper->changeBoxPriceUpdate($boxId);
                        return [];
                    });
                }
                $sendMesTitle = '【活动箱子】';
                break;
        }
        try {
            $results = $parallel->wait();
            return $results;
        } catch (ParallelExecutionException $e) {
            logger()->info($sendMesTitle . '异常:' . json_encode([
                    'results' => $e->getResults(),
                    'throwables' => $e->getThrowables(),
                ]));
            $message = [];
            foreach ($e->getThrowables() as $item) {
                $message[] = $item->getMessage();
            }
            \Ziyanco\Library\Sms\DingDingMessage::sendException(json_encode($message), $sendMesTitle . '异常:');
            //发送钉钉异常信息
            throw new \ErrorException('错误信息:' . $sendMesTitle . json_encode($message));
        }
        return [];
    }
}